package com.wing.productionPlan.service;


import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wing.common.utils.JsonResult;
import com.wing.enterprise.feign.EnterpriseClient;
import com.wing.enterprise.product.model.request.CustomerProductCatalogForm;
import com.wing.enterprise.product.model.request.ExternalProductForm;
import com.wing.enterprise.product.model.request.ProductReviewAddForm;
import com.wing.productionPlan.dao.DayTakeGoodsDao;
import com.wing.productionPlan.dao.RequirePlanDao;
import com.wing.productionPlan.enumeration.OperationEnumType;
import com.wing.productionPlan.enumeration.OrderSourceEnumType;
import com.wing.productionPlan.enumeration.TakeAuditEnumType;
import com.wing.productionPlan.model.entity.*;
import com.wing.productionPlan.model.response.DayTakeGoodsVO;
import com.wing.productionPlan.utils.CodeGeneratorUtils;
import com.wing.web.excel.DayTakeGoodsExcelln;
import com.wing.web.excel.RequirePlanExcelln;
import com.wing.web.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 *  日提货订单-ServiceImpl
 *
 * @author
 */
@Service
@Slf4j
public class DayTakeGoodsServiceImpl extends ServiceImpl<DayTakeGoodsDao, DayTakeGoods> implements DayTakeGoodsService {

    @Autowired
    RequirePlanItermService requirePlanItermService;

    @Autowired
    DayTakeGoodsProductService dayTakeGoodsProductService;

    @Autowired
    DayTakeGoodsItermService dayTakeGoodsItermService;

    /**
     * 分页查询任务列表
     *
     * @param pg
     * @param map
     * @return
     */
    @Override
    public Page<DayTakeGoodsVO> pageList4app(Page<DayTakeGoodsVO> pg, Map map) {
        List<DayTakeGoodsVO> vos = this.baseMapper.pageList4app(pg, map);
        pg.setRecords(vos);
        return pg;
    }

    @Override
    public DayTakeGoodsVO get4appById(Long id) {
        return baseMapper.get4appById(id);
    }

    @Override
    public void importExcel(List<DayTakeGoodsExcelln> list) {
        try {
            addExcel(list);
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
    }

    @Override
    @Transactional
    public JsonResult saveDayTakeGoods(DayTakeGoods dayTakeGoods) {

        try {
            dayTakeGoods.setTakeRecordNumber(CodeGeneratorUtils.generateCode());
            dayTakeGoods.setTakeOrderNumber(CodeGeneratorUtils.generateCodeNumber());
            dayTakeGoods.setSaveSource(OrderSourceEnumType.ADD.getData());
            dayTakeGoods.setSaveSourceCode(OrderSourceEnumType.ADD.getCode());
            dayTakeGoods.setContainedMaterialCount(dayTakeGoods.getDayTakeGoodsItermList().size());
            dayTakeGoods.setCreatorName(JwtUtils.getLoginUsername());
            dayTakeGoods.setCreator(JwtUtils.getLoginUserId());
            dayTakeGoods.setCreateTime(LocalDateTime.now());

            save(dayTakeGoods);

            for(int i=0;i<dayTakeGoods.getDayTakeGoodsItermList().size();i++){
                //take_iterm_number
                DayTakeGoodsIterm dayTakeGoodsIterm = new DayTakeGoodsIterm();
                BeanUtil.copyProperties(dayTakeGoods.getDayTakeGoodsItermList().get(i), dayTakeGoodsIterm,true);
                dayTakeGoodsIterm.setTakeGoodsId(dayTakeGoods.getId());
                dayTakeGoodsIterm.setTakeItermNumber(dayTakeGoods.getTakeOrderNumber()+"-"+(i+1));
                dayTakeGoodsIterm.setBelongTakeRecordNumber(dayTakeGoods.getTakeRecordNumber());
                dayTakeGoodsIterm.setTakeOrderNumber(dayTakeGoods.getTakeOrderNumber());
                dayTakeGoodsIterm.setTaskGoodsStatus(TakeAuditEnumType.FINISH.getCode());
                dayTakeGoodsIterm.setSaveSource(OrderSourceEnumType.ADD.getData());
                dayTakeGoodsIterm.setSaveSourceCode(OrderSourceEnumType.ADD.getCode());
                dayTakeGoodsIterm.setCreatorName(JwtUtils.getLoginUsername());
                dayTakeGoodsIterm.setCreator(JwtUtils.getLoginUserId());

                dayTakeGoodsIterm.setPlantCode(dayTakeGoods.getPlantCode());
                dayTakeGoodsIterm.setFactoryName(dayTakeGoods.getFactoryName());

                dayTakeGoodsItermService.save(dayTakeGoodsIterm);



                //同工厂、同采购组织、同一天、同一物料（行标签）、同产线，以最新的为准，如果有区别则新增一条
                DayTakeGoodsProduct dayTakeGoodsProduct= new DayTakeGoodsProduct();
                BeanUtil.copyProperties(dayTakeGoods.getDayTakeGoodsItermList().get(i), dayTakeGoodsProduct,true);
                dayTakeGoodsProduct.setTakeItermNumber(dayTakeGoods.getTakeOrderNumber()+"-"+(i+1));
                dayTakeGoodsProduct.setBelongTakeRecordNumber(dayTakeGoods.getTakeRecordNumber());
                dayTakeGoodsProduct.setTakeOrderNumber(dayTakeGoods.getTakeOrderNumber());
                dayTakeGoodsProduct.setTaskGoodsStatus(TakeAuditEnumType.FINISH.getCode());
                dayTakeGoodsProduct.setSaveSource(OrderSourceEnumType.ADD.getData());
                dayTakeGoodsProduct.setSaveSourceCode(OrderSourceEnumType.ADD.getCode());
                dayTakeGoodsProduct.setCreatorName(JwtUtils.getLoginUsername());
                dayTakeGoodsProduct.setCreator(JwtUtils.getLoginUserId());
                dayTakeGoodsProduct.setPlantCode(dayTakeGoods.getPlantCode());
                dayTakeGoodsProduct.setFactoryName(dayTakeGoods.getFactoryName());

                LambdaQueryWrapper<DayTakeGoodsProduct> wrapper1 = Wrappers.<DayTakeGoodsProduct>lambdaQuery()
                        .eq(DayTakeGoodsProduct::getPlantCode, dayTakeGoods.getPlantCode())
                        .eq(DayTakeGoodsProduct::getPurchaseTissue, dayTakeGoods.getDayTakeGoodsItermList().get(i).getPurchaseTissue())
                        .eq(DayTakeGoodsProduct::getReceiveMouthDate, dayTakeGoods.getDayTakeGoodsItermList().get(i).getReceiveMouthDate())
                        .eq(DayTakeGoodsProduct::getReceiveMouthDay, dayTakeGoods.getDayTakeGoodsItermList().get(i).getReceiveMouthDay())
                        .eq(DayTakeGoodsProduct::getSkuCode, dayTakeGoods.getDayTakeGoodsItermList().get(i).getSkuCode())
                        .eq(DayTakeGoodsProduct::getProductLine, dayTakeGoods.getDayTakeGoodsItermList().get(i).getProductLine());

                DayTakeGoodsProduct dayTakeGoodsProduct1 = dayTakeGoodsProductService.getOne(wrapper1);
                if(dayTakeGoodsProduct1!=null){
                    Long id = dayTakeGoodsProduct1.getId();
                    BeanUtil.copyProperties(dayTakeGoods.getDayTakeGoodsItermList().get(i), dayTakeGoodsProduct1,true);
                    dayTakeGoodsProduct1.setId(id);
                    dayTakeGoodsProductService.updateById(dayTakeGoodsProduct1);
                    generateInnerProductInfo(dayTakeGoodsProduct1);
               }else{
                    dayTakeGoodsProductService.save(dayTakeGoodsProduct);
                    generateInnerProductInfo(dayTakeGoodsProduct);
                }

            }
            return JsonResult.success("保存成功！");
        }catch (Exception e){
            e.printStackTrace();
        }

        return JsonResult.fail("保存失败！");
    }

    @Override
    public JsonResult updateDayTakeGoods(DayTakeGoods dayTakeGoods) {
        DayTakeGoods dayTakeGoods1 = this.baseMapper.selectById(dayTakeGoods.getId());
        if (dayTakeGoods1 == null) {
            return JsonResult.fail("修改失败！");
        }

        if (baseMapper.updateById(dayTakeGoods)>0) {
            QueryWrapper<DayTakeGoodsIterm> wrapper = new QueryWrapper<>();
            wrapper.lambda().eq(DayTakeGoodsIterm::getTakeGoodsId,dayTakeGoods.getId());
            dayTakeGoodsItermService.remove(wrapper);

            for(int i=0;i<dayTakeGoods.getDayTakeGoodsItermList().size();i++){
                DayTakeGoodsIterm dayTakeGoodsIterm = dayTakeGoods.getDayTakeGoodsItermList().get(i);
                dayTakeGoodsIterm.setTakeGoodsId(dayTakeGoods.getId());
                dayTakeGoodsIterm.setTakeItermNumber(dayTakeGoods.getTakeOrderNumber()+"-"+(i+1));
                dayTakeGoodsIterm.setBelongTakeRecordNumber(dayTakeGoods.getTakeRecordNumber());
                dayTakeGoodsIterm.setTakeOrderNumber(dayTakeGoods.getTakeOrderNumber());

                dayTakeGoodsIterm.setFactoryName(dayTakeGoods1.getFactoryName());
                dayTakeGoodsIterm.setPlantCode(dayTakeGoods1.getPlantCode());
            }

            //保存明细
            dayTakeGoodsItermService.saveBatch(dayTakeGoods.getDayTakeGoodsItermList());

        }
         return JsonResult.success();
    }

    @Transactional
    public void addExcel(List<DayTakeGoodsExcelln> list) {

        try {
            DayTakeGoods dayTakeGoods = new DayTakeGoods();
            dayTakeGoods.setTakeRecordNumber(CodeGeneratorUtils.generateCode());
            dayTakeGoods.setTakeOrderNumber(CodeGeneratorUtils.generateCodeNumber());
            dayTakeGoods.setSaveSource(OrderSourceEnumType.ADD.getData());
            dayTakeGoods.setSaveSourceCode(OrderSourceEnumType.ADD.getCode());
            dayTakeGoods.setContainedMaterialCount(list.size());

            dayTakeGoods.setPlantCode(list.get(0).getPlantCode());
            dayTakeGoods.setFactoryName(list.get(0).getFactoryName());

            dayTakeGoods.setCreatorName(JwtUtils.getLoginUsername());
            dayTakeGoods.setCreator(JwtUtils.getLoginUserId());
            dayTakeGoods.setCreateTime(LocalDateTime.now());

            save(dayTakeGoods);

            for(int i=0;i<list.size();i++){
                //take_iterm_number
                DayTakeGoodsIterm dayTakeGoodsIterm = new DayTakeGoodsIterm();
                BeanUtil.copyProperties(list.get(i), dayTakeGoodsIterm,true);
                dayTakeGoodsIterm.setTakeGoodsId(dayTakeGoods.getId());
                dayTakeGoodsIterm.setTakeItermNumber(dayTakeGoods.getTakeOrderNumber()+"-"+(i+1));
                dayTakeGoodsIterm.setBelongTakeRecordNumber(dayTakeGoods.getTakeRecordNumber());
                dayTakeGoodsIterm.setTakeOrderNumber(dayTakeGoods.getTakeOrderNumber());
                dayTakeGoodsIterm.setTaskGoodsStatus(TakeAuditEnumType.FINISH.getCode());
                dayTakeGoodsIterm.setSaveSource(OrderSourceEnumType.ADD.getData());
                dayTakeGoodsIterm.setSaveSourceCode(OrderSourceEnumType.ADD.getCode());
                dayTakeGoodsIterm.setCreatorName(JwtUtils.getLoginUsername());
                dayTakeGoodsIterm.setCreator(JwtUtils.getLoginUserId());

                dayTakeGoodsItermService.save(dayTakeGoodsIterm);

                DayTakeGoodsExcelln dayTakeGoodsExcelln = list.get(i);


                //同工厂、同采购组织、同一天、同一物料（行标签）、同产线，以最新的为准，如果有区别则新增一条
                DayTakeGoodsProduct dayTakeGoodsProduct= new DayTakeGoodsProduct();
                BeanUtil.copyProperties(list.get(i), dayTakeGoodsProduct,true);
                dayTakeGoodsProduct.setTakeItermNumber(dayTakeGoods.getTakeOrderNumber()+"-"+(i+1));
                dayTakeGoodsProduct.setBelongTakeRecordNumber(dayTakeGoods.getTakeRecordNumber());
                dayTakeGoodsProduct.setTakeOrderNumber(dayTakeGoods.getTakeOrderNumber());
                dayTakeGoodsProduct.setTaskGoodsStatus(TakeAuditEnumType.FINISH.getCode());
                dayTakeGoodsProduct.setSaveSource(OrderSourceEnumType.ADD.getData());
                dayTakeGoodsProduct.setSaveSourceCode(OrderSourceEnumType.ADD.getCode());
                dayTakeGoodsProduct.setCreatorName(JwtUtils.getLoginUsername());
                dayTakeGoodsProduct.setCreator(JwtUtils.getLoginUserId());

                LambdaQueryWrapper<DayTakeGoodsProduct> wrapper1 = Wrappers.<DayTakeGoodsProduct>lambdaQuery()
                        .eq(DayTakeGoodsProduct::getPlantCode, dayTakeGoodsExcelln.getPlantCode())
                        .eq(DayTakeGoodsProduct::getPurchaseTissue, dayTakeGoodsExcelln.getPurchaseTissue())
                        .eq(DayTakeGoodsProduct::getReceiveMouthDate, dayTakeGoodsExcelln.getReceiveMouthDate())
                        .eq(DayTakeGoodsProduct::getReceiveMouthDay, dayTakeGoodsExcelln.getReceiveMouthDay())
                        .eq(DayTakeGoodsProduct::getSkuCode, dayTakeGoodsExcelln.getSkuCode())
                        .eq(DayTakeGoodsProduct::getProductLine, dayTakeGoodsExcelln.getProductLine());
                DayTakeGoodsProduct dayTakeGoodsProduct1 = dayTakeGoodsProductService.getOne(wrapper1);
                if(dayTakeGoodsProduct1!=null){
                    Long id = dayTakeGoodsProduct1.getId();
                    BeanUtil.copyProperties(list.get(i), dayTakeGoodsProduct1,true);
                    dayTakeGoodsProduct1.setId(id);
                    dayTakeGoodsProductService.updateById(dayTakeGoodsProduct1);
                    generateInnerProductInfo(dayTakeGoodsProduct1);

                }else{
                    dayTakeGoodsProductService.save(dayTakeGoodsProduct);
                    generateInnerProductInfo(dayTakeGoodsProduct);
                }

             }
         }catch (Exception e){
            e.printStackTrace();
        }

    }



    @Autowired
    EnterpriseClient enterpriseClient;

    @Autowired
    RequirePlanDao requirePlanDao;

    public void generateInnerProductInfo(DayTakeGoodsProduct dayTakeGoodsProduct) {
        //判断内部产品有咩有1
        Long externalProductId= requirePlanDao.selExternalProductId(dayTakeGoodsProduct.getSkuCode());
        Long customerId = requirePlanDao.selCustomerId(dayTakeGoodsProduct.getFactoryName());

        if(externalProductId==null || externalProductId==0L){
            // 添加关联外部  	com_external_product  sel_customer_product_catalog

            CustomerProductCatalogForm customerProductCatalogForm=new CustomerProductCatalogForm();
            ExternalProductForm externalProductForm=new ExternalProductForm();

            externalProductForm.setCreatorName(JwtUtils.getLoginUsername());
            externalProductForm.setCreator(JwtUtils.getLoginUserId());

            externalProductForm.setCusSkuCode(dayTakeGoodsProduct.getSkuCode());
            externalProductForm.setCusProductName(dayTakeGoodsProduct.getSkuCode());
            externalProductForm.setCusProductSpec(dayTakeGoodsProduct.getMaterialDescribe());

            customerProductCatalogForm.setCustomerId(customerId);

            customerProductCatalogForm.setExternalProductForm(Arrays.asList(externalProductForm));
            enterpriseClient.addProduct(customerProductCatalogForm);
        }


        Long outerProductInfo = requirePlanDao.selIsInnerOuterProductInfo(dayTakeGoodsProduct.getSkuCode());
        if(outerProductInfo==null || outerProductInfo==0L){
            generateProductPreview(dayTakeGoodsProduct,customerId,externalProductId);
        }

    }


    public void generateProductPreview(DayTakeGoodsProduct dayTakeGoodsProduct, Long customerId, Long externalProductId){
        // externalProductId= requirePlanDao.selExternalProductId(dayTakeGoodsProduct.getSkuCode());
        //生成对应评审任务 222222222
        ProductReviewAddForm productReviewAddForm=new ProductReviewAddForm();

        productReviewAddForm.setCustomerId(customerId);
    /*    if(externalProductId!=null && externalProductId!=0L){
            productReviewAddForm.setCusSkuCode(externalProductId.toString());
        }*/
        productReviewAddForm.setCusSkuCode(dayTakeGoodsProduct.getSkuCode());
        productReviewAddForm.setCusProductCategory(dayTakeGoodsProduct.getMaterialType());
        //没 取得编码
        productReviewAddForm.setCusProductName(dayTakeGoodsProduct.getSkuCode());
        productReviewAddForm.setCusProductSpec(dayTakeGoodsProduct.getMaterialDescribe());
        productReviewAddForm.setCusProductUnit(dayTakeGoodsProduct.getMaterialUnit());
        productReviewAddForm.setCusProductCount(dayTakeGoodsProduct.getTakeGoodsCount());
        //todo 这个时间暂时没得
   /*     productReviewAddForm.setReviewEndTime();
        productReviewAddForm.setPlanGivenTime();*/
        //todo 部门目前写死的
        productReviewAddForm.setDepartmentId(9L);
        productReviewAddForm.setPostId(9L);
        productReviewAddForm.setPostName("仓管");
        productReviewAddForm.setReviewProcessId(1L);

        productReviewAddForm.setCustomerName(dayTakeGoodsProduct.getFactoryName());

        productReviewAddForm.setCreator(JwtUtils.getLoginUserId());

        JsonResult result= enterpriseClient.getOutProductId(dayTakeGoodsProduct.getSkuCode());
        if(result.getData()!=null){
            externalProductId=Long.valueOf(result.getData().toString());
        }

        //todo 在加一个产品ID
        productReviewAddForm.setExtProductId(externalProductId);
        enterpriseClient.addProductReview(productReviewAddForm);
    }




}

